package com.faxsun.api.wrapper.sku;

import java.math.BigDecimal;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlType;

import org.broadleafcommerce.common.file.service.StaticAssetPathService;
import org.broadleafcommerce.common.media.domain.Media;
import org.broadleafcommerce.core.catalog.dao.SkuDao;
import org.broadleafcommerce.core.catalog.domain.Sku;
import org.broadleafcommerce.core.inventory.service.InventoryService;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import com.faxsun.api.wrapper.inventory.InventoryWrapper;
import com.faxsun.api.wrapper.product.ProductConstants;

@Component("fsTreasureSkuWrapper")
@Scope("prototype")
@XmlRootElement(name = "fsTreasureSku")
@XmlAccessorType(value = XmlAccessType.FIELD)
@XmlType(name="fsTreasureSkuResource")
public class TreasureSkuWrapper extends org.broadleafcommerce.core.web.api.wrapper.SkuWrapper {
	@XmlTransient  
	@Resource(name = "blInventoryService")
    protected InventoryService inventoryService;
	
	@XmlTransient  
	@Resource(name="blSkuDao")
	private SkuDao skuDao;
	
	@XmlElement
	protected String urlOfSkuImage;
	
	@XmlElement
	protected InventoryWrapper inventory;
	
	@XmlElement
	protected BigDecimal displayOrder;
	
	public void wrapDetails(Sku model, HttpServletRequest request) {
		super.wrapDetails(model, request);
		
		this.displayOrder = model.getProduct().getAllParentCategoryXrefs().get(0).getDisplayOrder();
		
		if(model.isActive()){
			StaticAssetPathService staticAssetPathService = (StaticAssetPathService) this.context.getBean("blStaticAssetPathService");
			inventory = (InventoryWrapper)context.getBean("fsInventoryWrapper");
			Integer quantityAvailable = inventoryService.retrieveQuantityAvailable(model);
			inventory.wrapDetails(model, quantityAvailable, request);
			urlOfSkuImage = getUrl(model.getId());
			urlOfSkuImage = staticAssetPathService.convertAssetPath(urlOfSkuImage, request.getContextPath(), true);
		}				
	}
	
	@Override
    public void wrapSummary(Sku model, HttpServletRequest request) {
        wrapDetails(model, request);
    }
	
	private String getUrl(Long id){
		String url = null;
		Sku sku = skuDao.readSkuById(id);
	    assert sku != null;
	    Media media = sku.getSkuMedia().get(ProductConstants.PRIMARY);
	    if(media != null){
	    	url = media.getUrl();	
	    }
	   
		return url;
	}

}
